﻿namespace HK.Core.Utils
{
    /// <summary>
    /// 工具类 : 位相关运算.
    /// </summary>
    public static class UtilsBytes
    {
        /// <summary>
        /// 检测/检验指定位是否为1
        /// <para>  备注：可以同时检测多位</para>
        /// <para>  如：</para>
        /// <para>    iDstVale : 0x000000111</para>
        /// <para>    iCheckByte : 0x00000100</para>
        /// <para>  检测校验结果 : CheckBytes(0x000000111, 0x00000100) = 0x00000100 => true</para>
        /// </summary>
        /// <param name="iDstVale">目标值</param>
        /// <param name="iCheckByte">检测位</param>
        /// <returns>true:该位为1; false:该位不为1;</returns>
        public static bool CheckBytes(int iDstVale, int iCheckByte)
        {
            if (0x00000000 == iCheckByte) return iDstVale == iCheckByte;
            return (iDstVale & iCheckByte) == iCheckByte;
        }

        /// <summary>
        /// 设定字节位
        /// </summary>
        /// <param name="iDstVale">目标值</param>
        /// <param name="iBytesValue">字节位值</param>
        /// <param name="iOnOrOff">true:On; false:Off;</param>
        /// <returns>目标值</returns>
        public static int SetBytes(int iDstVale, int iBytesValue, bool iOnOrOff)
        {
            var value = iDstVale;
            if (iOnOrOff) 
            {
                value |= iBytesValue;
            } 
            else 
            {
                if (0 == iBytesValue)
                {
                    value = 0;
                }
                else
                {
                    value &= ~iBytesValue;
                }
            }
            return value;
        }
    }
}